package com.scheduled;

import com.gavel.database.SQLExecutor;
import com.gavel.utils.StringUtils;
import com.google.gson.Gson;
import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.mrobuy.jd.JdClientFactory;
import com.mrobuy.jd.api.Jos;
import com.mrobuy.jd.api.ProductInfoFindClient;
import com.mrobuy.jdvc.dao.*;
import com.mrobuy.jdvc.entity.*;
import com.mrobuy.util.IdentifierGen;
import com.mrobuy.util.MD5Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 店铺类目信息同步
 *
 */
@Component
public class CategorySyncTask {

    private static Logger LOG = LoggerFactory.getLogger(CategorySyncTask.class);

    @Autowired
    private JDAccountDao jdAccountDao;

    @Autowired
    private VCCategotyDao vcCategotyDao;

    @Autowired
    private VCBrandDao vcBrandDao;

    @Autowired
    private CommonDao commonDao;


    private final AtomicBoolean running = new AtomicBoolean(false);

    @Scheduled(cron="0 0 1 * * ?")
    // @Scheduled(fixedRate = 1000*60*60)
    public void categotySync() {

        if ( !TaskSwitch.CATE_SYNC.get() ) {
            return;
        }

        LOG.info("Start...");
        if ( running.compareAndSet(false, true) ) {
            List<JDAccount> accounts = jdAccountDao.list();
            if ( accounts!=null ) {
                for (JDAccount account : accounts) {
                    if ( "Y".equalsIgnoreCase(account.getAutoSync()) ) {
                        try {
                            LOG.info("[店铺: {}]类目同步.", account.getName());
                            cateSync(account);
                        } catch (Exception e) {
                            LOG.error("[店铺: {}]类目同步异常: {}", account.getName(), e.getMessage(), e.getCause());
                        }

                        try {
                            LOG.info("[店铺: {}]品牌同步.", account.getName());
                            brandSync(account);
                        } catch (Exception e) {
                            LOG.error("[店铺: {}]品牌同步异常: {}", account.getName(), e.getMessage(), e.getCause());
                        }

                        try {
                            LOG.info("[店铺: {}]类目规格属性同步.", account.getName());
                            propSync(account);
                        } catch (Exception e) {
                            LOG.error("[店铺: {}]类目规格属性同步异常: {}", account.getName(), e.getMessage(), e.getCause());
                        }

                        try {
                            LOG.info("[店铺: {}]类目扩展属性同步.", account.getName());
                            extPropSync(account);
                        } catch (Exception e) {
                            LOG.error("[店铺: {}]类目扩展属性同步异常: {}", account.getName(), e.getMessage(), e.getCause());
                        }

                        try {
                            LOG.info("[店铺: {}]类目销售属性同步.", account.getName());
                            salePropSync(account);
                        } catch (Exception e) {
                            LOG.error("[店铺: {}]类目销售属性同步异常: {}", account.getName(), e.getMessage(), e.getCause());
                        }
                    }
                }
            }
            running.set(false);
        }

        LOG.info("Done.");
    }

    private void cateSync(JDAccount account) throws Exception {

        JdClient client = new DefaultJdClient(JdClientFactory.serverUrl, account.getAccess_token(), account.getAppkey(), account.getAppsecret());
        String vendor = account.getVccode();


        List<VCCategory> vcCategories = Jos.categoryFindClient(client).call();

        for (VCCategory vcCategory : vcCategories) {
            try {
                VCCategory exist = vcCategotyDao.load(String.valueOf(vcCategory.getId()), vendor);
                if ( exist!=null ) {
                    continue;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


            JDCategory parent = SQLExecutor.executeQueryBean("select * from JD_CATEGORY where CID = ? ", JDCategory.class, vcCategory.getId());
            if ( parent!=null ) {
                vcCategory.setPid(parent.getPid());
                parent = SQLExecutor.executeQueryBean("select * from JD_CATEGORY where CID = ? ", JDCategory.class, parent.getPid());
                if ( parent!=null ) {
                    vcCategory.setPname(parent.getName());
                }
            }

            vcCategory.setVccode(account.getVccode());
            vcCategotyDao.insert(vcCategory);
        }
    }


    private void brandSync(JDAccount account) throws Exception {

        JdClient client = new DefaultJdClient(JdClientFactory.serverUrl, account.getAccess_token(), account.getAppkey(), account.getAppsecret());
        String vendor = account.getVccode();

        List<VCBrand> vcBrandList = Jos.brandFindClient(client).call();

        for (VCBrand vcBrand : vcBrandList) {

            try {
                VCBrand exist = vcBrandDao.load(String.valueOf(vcBrand.getBrandid()), vendor);
                if ( exist!=null ) {
                    continue;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            vcBrand.setVendor(vendor);
            if (StringUtils.isBlank(vcBrand.getId())) {
                vcBrand.setId(MD5Utils.md5Hex(vendor + "_" + vcBrand.getBrandid()).trim().toUpperCase());
            }

            vcBrandDao.insert(vcBrand);
        }

    }

    private void propSync(JDAccount account) {

        JdClient client = new DefaultJdClient(JdClientFactory.serverUrl, account.getAccess_token(), account.getAppkey(), account.getAppsecret());
        String vendor = account.getVccode();

        List<VCCategory> categories =  commonDao.queryList("select * from VC_CATEGORY where LEVEL = '3' and VCCODE = ? ", VCCategory.class, vendor);
        for (VCCategory category : categories) {
            System.out.println(category);
            Integer cid = category.getId();

            try {
                commonDao.execute("delete from VC_CATEGORY_PROP where CID = ?", cid);
                commonDao.execute("delete from VC_PROP_VALUE where CID = ?", cid);
                List<VCCategoryProp>  props = Jos.propFindClient(client)
                        .setCid3(cid)
                        .call();

                for (VCCategoryProp prop : props) {
                    prop.setId(IdentifierGen.uuid());
                    commonDao.insert(prop);
                    if ( prop.getOptions()!=null ) {
                        for (VCPropValue propValue : prop.getOptions()) {
                            propValue.setId(IdentifierGen.uuid());
                            commonDao.insert(propValue);
                        }
                    }
                }
            } catch (Exception e) {

            }
        }
    }


    private void extPropSync(JDAccount account) {

        JdClient client = new DefaultJdClient(JdClientFactory.serverUrl, account.getAccess_token(), account.getAppkey(), account.getAppsecret());
        String vendor = account.getVccode();

        List<VCCategory> categories =  commonDao.queryList("select * from VC_CATEGORY where LEVEL = '3' and VCCODE = ? ", VCCategory.class, vendor);
        for (VCCategory category : categories) {
            System.out.println(category);
            Integer cid = category.getId();

            try {
                commonDao.execute("delete from VC_CATEGORY_EXTPROP where CID = ?", cid);
                commonDao.execute("delete from VC_EXTPROP_VALUE where CID = ?", cid);

                List<VCCategoryExtProp>  props = Jos.extPropFindClient(client)
                        .setCid3(cid)
                        .call();

                for (VCCategoryExtProp prop : props) {
                    prop.setId(IdentifierGen.uuid());
                    commonDao.insert(prop);
                    if ( prop.getOptions()!=null ) {
                        for (VCExtPropValue propValue : prop.getOptions()) {
                            propValue.setId(IdentifierGen.uuid());
                            commonDao.insert(propValue);
                        }
                    }
                }
            } catch (Exception e) {

            }
        }
    }

    private void salePropSync(JDAccount account) {

        JdClient client = new DefaultJdClient(JdClientFactory.serverUrl, account.getAccess_token(), account.getAppkey(), account.getAppsecret());
        String vendor = account.getVccode();

        List<VCCategory> categories =  commonDao.queryList("select * from VC_CATEGORY where LEVEL = '3' and VCCODE = ? ", VCCategory.class, vendor);
        for (VCCategory category : categories) {
            System.out.println(category);
            Integer cid = category.getId();

            try {
                commonDao.execute("delete from VC_CATEGORY_SALE_PROP where CID = ?", cid);

                List<VCCategorySaleProp> saleProps = Jos.salePropFindClient(client)
                        .setCid3(cid)
                        .call();

                for (VCCategorySaleProp saleProp : saleProps) {
                    saleProp.setId(IdentifierGen.uuid());
                    commonDao.insert(saleProp);
                }
            } catch (Exception e) {

            }
        }
    }
}
